package com.eva.core.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Date;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * 登录用户信息
 */
@Data
@ApiModel("登录用户信息")
public class LoginUserInfo implements UserDetails {

    @ApiModelProperty("主键")
    private Integer id;

    @ApiModelProperty("用户名")
    private String username;

    @ApiModelProperty("真实姓名")
    private String realName;

    @ApiModelProperty("头像")
    private String avatar;

    @ApiModelProperty("生日")
    private Date birthday;

    @ApiModelProperty("性别")
    private String gender;

    @ApiModelProperty("角色标识符集")
    private Set<String> roles;

    @ApiModelProperty("权限标识符集")
    private Set<String> permissions;

    @ApiModelProperty("是否为超级管理员")
    private Boolean isSuperAdmin;

    @JsonIgnore
    @ApiModelProperty("菜单权限主键集")
    private Set<Integer> menuPermissionIds;

    @JsonIgnore
    @ApiModelProperty("功能权限主键集")
    private Set<Integer> menuFuncPermissionIds;

    @JsonIgnore
    @ApiModelProperty("系统配置权限主键集")
    private Set<Integer> systemConfigPermissionIds;

    @JsonIgnore
    @ApiModelProperty("盐值")
    private String salt;

    @JsonIgnore
    @ApiModelProperty("密码")
    private String password;

    /**
     * 获取授权集合
     * 注意：Spring Security中并不会直接区分角色和权限，统一视为授权，所以角色编码和权限编码不能一致
     */
    @JsonIgnore
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Set<GrantedAuthority> authorities = new HashSet<>();
        // 添加角色
        if (this.roles != null) {
            for (String role : this.roles) {
                authorities.add(new SimpleGrantedAuthority(role));
            }
        }
        // 添加权限
        if (this.permissions != null) {
            for (String permission : this.permissions) {
                authorities.add(new SimpleGrantedAuthority(permission));
            }
        }
        return authorities;
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isEnabled() {
        return true;
    }

}
